﻿using System;

namespace BizElements.Core
{
    internal static class DbRelationConfigurationUtil
    {
        internal static DbRelation CreateRelation(IDbRelationConfiguration relationConfig)
        {
            IDbTable parent = relationConfig.CreateParent();
            IDbColumn[] parentPkCols = GetParentPrimayKeyColumns(relationConfig, parent);

            IDbTable child = relationConfig.CreateChild();
            IDbColumn[] childFkCols = GetChildForeignKeyColumns(relationConfig, child);

            DbRelation rel = new DbRelation(parent, parentPkCols, child, childFkCols, null);
            return rel;
        }

        internal static IDbColumn[] GetChildForeignKeyColumns(IDbRelationConfiguration relationConfig, IDbTable child)
        {
            IDbColumn[] childFkCols = new IDbColumn[relationConfig.ChildForeignKeyColumnNames.Length];
            int childFkPart = 0;
            foreach (string childFkColName in relationConfig.ChildForeignKeyColumnNames)
            {
                childFkCols[childFkPart] = child.Columns.GetByColumnName(childFkColName);
                childFkPart++;
            }

            return childFkCols;
        }

        internal static IDbColumn[] GetParentPrimayKeyColumns(IDbRelationConfiguration relationConfig, IDbTable parent)
        {
            IDbColumn[] parentPkCols = new IDbColumn[relationConfig.ParentPrimaryKeyColumnNames.Length];
            int parentPkPart = 0;
            foreach (string parentPkColName in relationConfig.ParentPrimaryKeyColumnNames)
            {
                parentPkCols[parentPkPart] = parent.Columns.GetByColumnName(parentPkColName);
                parentPkPart++;
            }

            return parentPkCols;
        }
    }
}
